package com.example.social.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.social.api.ApiClient.threadApiService
import com.example.social.api.ApiClient.userApiService
import com.example.social.api.BaseResponse

import com.example.social.model.ThreadModel
import com.example.social.model.UserModel

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class UserViewModel : ViewModel() {

    //关注数
    private val _followerList = MutableLiveData(setOf<String>())
    val followerList: LiveData<Set<String>> get() = _followerList

    //正在关注数
    private val _followingList = MutableLiveData(setOf<String>())
    val followingList: LiveData<Set<String>> get() = _followingList

    private val _users = MutableLiveData(UserModel())
    val users: LiveData<UserModel> get() = _users

    private val _threads = MutableLiveData(listOf<ThreadModel>())
    val threads: LiveData<List<ThreadModel>> get() = _threads

    private val _error = MutableLiveData<String>()
    val error: LiveData<String> get() = _error

    private val _errorShown = MutableLiveData(false)
    val isErrorShown: LiveData<Boolean> get() = _errorShown

    // 设置错误信息
    fun setError(message: String) {
        _error.value = message
        _errorShown.value = false // 每次设置新错误时重置
    }

    // 标记错误信息已经显示
    fun markErrorAsShown() {
        _errorShown.value = true
    }


    //uid 查询用户
    fun fetchUser(uid: String) {
        val call = userApiService.getUserById(uid)
        call.enqueue(object : Callback<BaseResponse<UserModel>> {
            override fun onResponse(
                call: Call<BaseResponse<UserModel>>,
                response: Response<BaseResponse<UserModel>>
            ) {
                if (response.isSuccessful) {
                    val result = response.body()
                    if (result?.code == 0) {
                        _users.postValue(result.data)
                        Log.e("fetchUser", result.data.toString())
                    } else {
                        Log.e(
                            "UserViewModel fetchUser",
                            "查询用户失败"
                        )
                    }
                }
            }

            override fun onFailure(call: Call<BaseResponse<UserModel>>, t: Throwable) {
                Log.e(
                    "UserViewModel fetchUser",
                    "查询用户失败", t
                )
            }

        })
    }


    fun fetchThreads(uid: String) {
        val call = threadApiService.getThreadsById(uid)
        call.enqueue(object : Callback<BaseResponse<List<ThreadModel>>> {
            override fun onResponse(
                call: Call<BaseResponse<List<ThreadModel>>>,
                response: Response<BaseResponse<List<ThreadModel>>>
            ) {
                if (response.isSuccessful) {
                    val list = response.body()?.data
                    _threads.postValue(list)
                } else {
                    Log.e(
                        "UserViewModel fetchThreads",
                        "获取用户话题失败 : ${response.errorBody()?.string()}"
                    )
                }
            }

            override fun onFailure(call: Call<BaseResponse<List<ThreadModel>>>, t: Throwable) {
                Log.e(
                    "UserViewModel fetchThreads",
                    "获取用户话题失败", t
                )
            }

        })
    }


    fun followUsers(userId: String, followUserId: String) {
        val call = userApiService.followUser(userId, followUserId)
        call.enqueue(object : Callback<BaseResponse<String>> {
            override fun onResponse(
                call: Call<BaseResponse<String>>,
                response: Response<BaseResponse<String>>
            ) {
                if (response.isSuccessful && response.body()?.code == 0) {
                    setError("关注成功!")
                    getFollowers(followUserId)
                } else {
                    setError("关注失败,系统异常")
                    Log.e(
                        "UserViewModel followUsers",
                        "关注失败 : ${response.errorBody()?.string()}"
                    )
                }
            }

            override fun onFailure(call: Call<BaseResponse<String>>, t: Throwable) {
                setError("关注失败,系统异常")
                Log.e("UserViewModel followUsers", "请求失败", t)
            }

        })
    }

    fun unfollowUser(currentId: String, unfollowUserId: String) {
        val call = userApiService.unfollowUser(currentId, unfollowUserId)
        call.enqueue(object : Callback<BaseResponse<String>> {
            override fun onResponse(
                call: Call<BaseResponse<String>>,
                response: Response<BaseResponse<String>>
            ) {
                if (response.isSuccessful && response.body()?.code == 0) {
                    setError("取消关注成功!")
                    getFollowers(unfollowUserId)
                }else{
                    setError("取消关注失败,系统异常")
                }
            }

            override fun onFailure(call: Call<BaseResponse<String>>, t: Throwable) {
                setError("取消关注失败,系统异常")
                Log.e("UserViewModel unfollowUser", "请求失败", t)
            }

        })
    }


    fun getFollowing(userId: String) {
        val call = userApiService.getFollowList(userId)
        call.enqueue(object : Callback<BaseResponse<Set<String>>> {
            override fun onResponse(
                call: Call<BaseResponse<Set<String>>>,
                response: Response<BaseResponse<Set<String>>>
            ) {
                if (response.isSuccessful) {
                    val list = response.body()!!.data
                    _followingList.postValue(list)
                } else {
                    // 处理获取失败的情况
                    Log.e(
                        "UserViewModel getFollowers",
                        "获取用户被关注信息失败: ${response.errorBody()?.string()}"
                    )
                }
            }

            override fun onFailure(call: Call<BaseResponse<Set<String>>>, t: Throwable) {
                Log.e("UserViewModel getFollowers", "请求失败", t)
            }

        })


    }

    fun getFollowers(userId: String) {
        val call = userApiService.getFollowedList(userId)
        call.enqueue(object : Callback<BaseResponse<Set<String>>> {
            override fun onResponse(
                call: Call<BaseResponse<Set<String>>>,
                response: Response<BaseResponse<Set<String>>>
            ) {
                if (response.isSuccessful) {
                    val list = response.body()!!.data
                    _followerList.postValue(list)
                } else {
                    // 处理获取失败的情况
                    Log.e(
                        "UserViewModel getFollowing",
                        "获取用户关注信息失败: ${response.errorBody()?.string()}"
                    )
                }
            }

            override fun onFailure(call: Call<BaseResponse<Set<String>>>, t: Throwable) {
                Log.e("UserViewModel getFollowing", "请求失败", t)
            }

        })

    }
}

